package cn.com.callback

import cn.com.elite.Util
import cn.com.kh.HttpClientProxy
import cn.com.kh.KHDBConfig

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.elite.EliteBean
import net.sf.json.JSONObject;


public class autoSendMessage implements CallBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(autoSendMessage.class);


    public void doCallBack(EliteBean eliteBean, String callBack, Map map, String paramString) {

        eliteBean.update("update webloginlist set CHECKDBTIME = NOW()", "dataSource");

        log.warn("---autoSendMessage---");
        //查找待发送任务
        List getSmsSelectSQL = eliteBean.chaxun_sql("Select D.Documentout_Guid," +
                "       D.Doctype," +
                "       D.Documentpath," +
                "       D.Documentpath2," +
                "       D.Lockedby," +
                "       D.OpenId," +
                "       D.Template_Id," +
                "       D.Stringfield1," +
                "       D.Documentto," +
                "       o.workorderid," +
                "       wm.MAPNAME" +
                "  From Documentout D" +
                "  LEFT JOIN  OBJECTIVE O ON D.OBJECTIVE_GUID=O.OBJECTIVE_GUID" +
                "  LEFT JOIN  wo3_frame_map wm ON wm.map_id=O.map_id" +
                " Where D.Doctype In (3,4,5,6)" +
                "   And D.Status = 3" +
                "   And D.DOCUMENTTO!=''" +
                "   And D.DOCUMENTTO!='null'" +
                "   And D.Trialcount < D.Trialcountlimit" +
                "   And Ifnull(D.Expectedstartdate, Now()) <= Now()" +
                " Order By D.Priority_Id, D.Expectedstartdate Limit 200", "dataSource");
        log.debug("SQL获取待发送数据量:" + getSmsSelectSQL.size());

        for (int i = 0; i < getSmsSelectSQL.size(); i++) {

            Map selectResultcm = getSmsSelectSQL.get(i);
            String Documentout_Guid = selectResultcm.get("Documentout_Guid");
            String Doctype = selectResultcm.get("Doctype");
            String Documentto = selectResultcm.get("Documentto");
            String Documentpath = selectResultcm.get("Documentpath");
            String Documentpath2 = selectResultcm.get("Documentpath2");
            String Template_Id = selectResultcm.get("Template_Id");
            String Open_Id = selectResultcm.get("OpenId");
            String URL = selectResultcm.get("Stringfield1");
            String opsource = selectResultcm.get("Lockedby");
            String workorderid = selectResultcm.get("workorderid");
            String MAPNAME = selectResultcm.get("MAPNAME");

            if (Doctype == "3") {
                doSendSMS(eliteBean, Documentout_Guid, Documentto, Documentpath);

            } else if (Doctype == "4") {
                doSendWXGZH(eliteBean, Documentout_Guid, Documentto, Template_Id, URL, Documentpath2, opsource);

            } else if (Doctype == "5") {
                doSendWXMiniP(eliteBean, Documentout_Guid, Documentto, Template_Id, URL, Documentpath2, opsource);

            } else if (Doctype == "6") {
                dosendDBCApp(eliteBean, Documentout_Guid, Documentto, Documentpath, workorderid, MAPNAME);

            } else {
                log.warn("未知的消息类型-本条任务结束");
            }
        }

    }

    /**
     * 发送短信消息
     * @param s1
     * @param s2
     * @param s3
     */
    public static void doSendSMS(EliteBean eliteBean, String Documentout_Guid, String Documentto, String Documentpath) {

        // 开始准备发送
        JSONObject sendResultJson = sendLTsms(eliteBean, Documentto, Documentpath);

        if (sendResultJson.getString("resultcode") == "0") {
            // 发送成功
            eliteBean.update("Update Documentout Set Status = '1', Trialcount = Trialcount + 1, Lasttrydatetime = Now(), Finishdatetime = Now() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        } else {
            // 发送失败
            String failCode = sendResultJson.getString("resultcode");
            String failDesc = sendResultJson.getString("resultdesc");
            eliteBean.update("Update Documentout Set Status = Case When Trialcount + 1 >= Trialcountlimit Then '-1' Else Status End, Failcode = '" + failCode + "', Faildescription = '" + failDesc + "', Trialcount = Trialcount + 1, Lasttrydatetime = Now() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        }

    }


    /**
     * 发送APP消息
     * @param s1
     * @param s2
     * @param s3
     */
    public static void dosendDBCApp(EliteBean eliteBean, String Documentout_Guid, String Documentto, String Documentpath, workorderid, MAPNAME) {

        // 开始准备发送
        JSONObject sendResultJson = sendDBCApp(eliteBean, Documentto, Documentpath, workorderid, MAPNAME);
        //String sendRes=sendDBCApp(eliteBean, Documentto, Documentpath);
        log.debug("结果：" + sendResultJson.toString());


        if (sendResultJson.getString("resultcode") == "0") {
            // 发送成功
            eliteBean.update("Update Documentout Set Status = '1', Trialcount = Trialcount + 1, Lasttrydatetime = Now(), Finishdatetime = Now() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        } else {
            // 发送失败
            String failCode = sendResultJson.getString("resultcode");
            String failDesc = sendResultJson.getString("resultdesc");
            eliteBean.update("Update Documentout Set Status = Case When Trialcount + 1 >= Trialcountlimit Then '-1' Else Status End, Failcode = '" + failCode + "', Faildescription = '" + failDesc + "', Trialcount = Trialcount + 1, Lasttrydatetime = Now() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        }

    }


    /**
     * 发送公众号消息
     * @param s1
     * @param s2
     */
    public static void doSendWXGZH(EliteBean eliteBean, String Documentout_Guid, String Open_Id, String Template_Id, String url, String Template_Data, String opsource) {
        int code = 0;
        String msgid = "";
        String msg = "";
        try {
            String apiWXSendTemplateURL = KHDBConfig.getAPIURL(eliteBean, "Groovy-Inner") + "/api/apiWXSendTemplate?opsource=" + opsource;
            JSONObject postBody = new JSONObject();
            JSONObject postData = JSONObject.fromObject(Template_Data);
            postBody.put("touser", Open_Id);
            postBody.put("template_id", Template_Id);
            postBody.put("topcolor", "#FF0000");
            postBody.put("url", url);
            postBody.put("data", postData);
            log.debug("待发送公众号模板消息URL：" + apiWXSendTemplateURL + " 发送内容:" + postBody.toString());

            // 调用发送公众号模板接口
            String sendResult = HttpClientProxy.sendPost(apiWXSendTemplateURL, postBody.toString(), "", 5000);
            JSONObject sendResultJson = JSONObject.fromObject(sendResult);

            // 解析发送返回结果
            code = sendResultJson.getInt("code");
            msg = sendResultJson.getString("msg");
            msgid = sendResultJson.getJSONObject("data").getString("msgid");
        } catch (Exception e1) {
            log.error("发送公众号模板处理异常", e1);
            code = -1;
        }

        if (code == 1) {
            // 发送成功
            eliteBean.update("Update Documentout Set Status = '1', Trialcount = Trialcount + 1, Lasttrydatetime = Now(), Finishdatetime = Now(), Msgid = '" + msgid + "' Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        } else {
            // 发送失败
            eliteBean.update("Update Documentout Set Status = Case When Trialcount + 1 >= Trialcountlimit Then '-1' Else Status End, Failcode = '" + code + "', Faildescription = '" + msg + "', Trialcount = Trialcount + 1, Lasttrydatetime = Now() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        }
        log.debug("发送公众号模板处理完成...");

    }

    /**
     * 发送小程序消息
     * @param s1
     * @param s2
     */
    public static void doSendWXMiniP(EliteBean eliteBean, String Documentout_Guid, String Open_Id, String Template_Id, String url, String Template_Data, String opsource) {
        int code = 0;
        String msgid = "";
        String msg = "";
        try {
            String apiWXSendTemplateURL = KHDBConfig.getAPIURL(eliteBean, "NGS-Local") + "/ngsapitask/api/apiWXSendTemplate?opsource=" + opsource;
            JSONObject postBody = new JSONObject();
            JSONObject postData = JSONObject.fromObject(Template_Data);
            postBody.put("touser", Open_Id);
            postBody.put("template_id", Template_Id);
            postBody.put("miniprogram_state", "trial");
            postBody.put("lang", "zh_CN");
            postBody.put("page", url);
            postBody.put("data", postData);
            log.debug("待发送小程序消息URL：" + apiWXSendTemplateURL + " 发送内容:" + postBody.toString());

            // 调用发送公众号模板接口
            String sendResult = HttpClientProxy.sendPost(apiWXSendTemplateURL, postBody.toString(), "", 5000);
            JSONObject sendResultJson = JSONObject.fromObject(sendResult);

            // 解析发送返回结果
            code = sendResultJson.getInt("code");
            msg = sendResultJson.getString("msg");
            msgid = sendResultJson.getJSONObject("data").getString("msgid");
        } catch (Exception e1) {
            log.error("发送小程序模板处理异常", e1);
            code = -1;
        }

        if (code == 1) {
            // 发送成功
            eliteBean.update("Update Documentout Set Status = '1', Trialcount = Trialcount + 1, Lasttrydatetime = Now(), Finishdatetime = Now(), Msgid = '" + msgid + "' Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        } else {
            // 发送失败
            eliteBean.update("Update Documentout Set Status = Case When Trialcount + 1 >= Trialcountlimit Then '-1' Else Status End, Failcode = '" + code + "', Faildescription = '" + msg + "', Trialcount = Trialcount + 1, Lasttrydatetime = Now() Where Documentout_Guid = '" + Documentout_Guid + "'", "dataSource");
        }
        log.debug("发送小程序模板处理完成...");

    }


    public static JSONObject sendLTsms(EliteBean eliteBean, String Documentto, String Documentpath) {
        String charset = "GBK"; //设置字符集
        int timeout = 100000; //设置请求超时时间
        int enableSSLflag = 1;

        JSONObject result = new JSONObject();

        //获取联通企业编号
        String SpCode = KHDBConfig.getParam(eliteBean, "SMS-ID");
        //获取联通用户名称
        String LoginName = KHDBConfig.getParam(eliteBean, "SMS-LN");
        //获取联通用户密钥
        String Password = KHDBConfig.getParam(eliteBean, "SMS-KE");
        //获取联通短信发送地址
        String url = KHDBConfig.getAPIURL(eliteBean, "SMS-URL");

        log.warn("---autoSendMessage---");

        try {

            StringBuffer formdata = new StringBuffer();
            formdata.append("SpCode=" + SpCode);
            formdata.append("&LoginName=" + LoginName);
            formdata.append("&Password=" + Password);
            formdata.append("&SerialNumber=&ScheduleTime=&f=1");
            formdata.append("&MessageContent=" + Documentpath);
            formdata.append("&UserNumber=" + Documentto);

            def sendResult = Util.doHttpPost(url, formdata.toString(), charset, timeout, enableSSLflag);
            log.debug("短信发送结果：" + sendResult);
            Map<String, Object> map = transStringToMap(sendResult, "&", "=");
            String resultcode = "";
            String resultdesc = "";
            for (String key : map.keySet()) {
                System.out.println("key:" + key + ", value:" + map.get(key));
                if (key == "result") {
                    resultcode = map.get(key);
                }
                if (key == "description") {
                    resultdesc = map.get(key);
                }

            }
            result.put("resultcode", resultcode);
            result.put("resultdesc", resultdesc);
            return result;


        } catch (Exception e) {
            log.error("errormsg:", e)
            result.put("resultcode", "-1");
            result.put("resultdesc", "接口调用错误！");
            return result;
        }
    }


    public static JSONObject sendDBCApp(EliteBean eliteBean, String Documentto, String Documentpath, workorderid, MAPNAME) {
        String charset = "UTF-8"; //设置字符集
        int timeout = 100000; //设置请求超时时间
        int enableSSLflag = 0;

        JSONObject result = new JSONObject();
        //获取APP发送地址
        String url = KHDBConfig.getAPIURL(eliteBean, "APP-SEND");
        log.warn("---autoAppSendMessage---");
        try {
            StringBuffer formdata = new StringBuffer();
            formdata.append("loginname=" + Documentto);
            formdata.append("&orderid=" + workorderid);
            formdata.append("&ordertype=" + MAPNAME);
            formdata.append("&content=" + Documentpath);
            def sendAppResult = Util.doHttpPost(url, formdata.toString(), charset, timeout, enableSSLflag);
            log.error("APP发送结果：" + sendAppResult);
            JSONObject obj = JSONObject.fromObject(sendAppResult);
            result.put("resultcode", obj.get("code"));
            result.put("resultdesc", obj.get("descs"));
            return result;
        } catch (Exception e) {
            log.error("errormsg:", e);
            result.put("resultcode", "-1");
            result.put("resultdesc", "接口调用错误！");
            return result;
        }
    }


    public static Map<String, Object> transStringToMap(String mapString, String separator, String pairSeparator) {
        Map<String, Object> map = new HashMap<String, Object>();
        String[] fSplit = mapString.split(separator);
        for (int i = 0; i < fSplit.length; i++) {
            if (fSplit[i] == null || fSplit[i].length() == 0) {
                continue;
            }
            String[] sSplit = fSplit[i].split(pairSeparator);
            String value = fSplit[i].substring(fSplit[i].indexOf('=') + 1, fSplit[i].length());
            map.put(sSplit[0], value);
        }

        return map;
    }

}
